package service

import (
	"context"
	"flag"
	"github.com/go-kit/kit/endpoint"
	"golang.org/x/time/rate"
	"strconv"
	"webdemo/src/go-kit/utils"
)

type UserRequest struct {
	Uid    int    `json:"uid"`
	Method string `json:"method"`
}

type UserResponse struct {
	Result string `json:"result"`
}

// 限流中间件
func RateLimit(limit *rate.Limiter) endpoint.Middleware {
	return func(endpoint endpoint.Endpoint) endpoint.Endpoint {
		return func(ctx context.Context, request interface{}) (response interface{}, err error) {
			if !limit.Allow() {
				//return nil, errors.New("too many request")
				// 自定义异常
				return nil, utils.NewError(500, "too many request")
			}
			return endpoint(ctx, request)

		}
	}
}

func GenUserEndpoint(service IUserService) endpoint.Endpoint {
	port := flag.Int("port", 0, "端口")
	return func(ctx context.Context, request interface{}) (response interface{}, err error) {
		req := request.(UserRequest)
		result := ""
		if req.Method == "GET" {
			result = service.GetName(req.Uid) + strconv.Itoa(*port)
		} else if req.Method == "DELETE" {
			err := service.DelName(req.Uid)
			if err != nil {
				result = err.Error()
			} else {
				result = "success"
			}
		}
		return UserResponse{
			Result: result,
		}, nil
	}
}
